<!--
 * @Author: canlong.shen
 * @Date: 2021-10-21 16:57:26
 * @LastEditors: your name
 * @LastEditTime: 2021-10-25 16:21:17
 * @Description: file content
-->
<html>
  <head>
    <title>课08.Vuex的五大核心——Action</title>
    <!-- vue -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <!-- vuex -->
    <script src="https://unpkg.com/vuex@3.6.2/dist/vuex.js"></script>
  </head>
  <body>
    <div id="app"></div>
    <script>
      const store = new Vuex.Store({
        state: {
          count: 1,
        },
        mutations: {
          increment(state) {
            state.count++
          },
        },
        actions: {
          incrementAsync({ commit }) {
            commit("increment")
          },
          actionA(context, payload) {
            return  new Promise((resolve, reject) => {
              setTimeout(() => {
                console.log("action A 提交")
                context.commit("increment")
                resolve()
              }, 1000)
            })
          },
          actionB(context, payload) {
            console.log("actionB")
            context.dispatch("actionA").then((res) => {
            console.log("执行完 action A")
              context.commit("increment")
            })
          },
        },
      })

      const Counter = {
        template: `
         <div>
          {{count}}
          <button @click="addCount">触发</button>
          </div>`,
        data() {
          return {}
        },
        methods: {
          addCount() {
              this.$store.dispatch("actionB")
          },
          ...Vuex.mapActions(["incrementAsync"]),
        },
        computed: {
          ...Vuex.mapState(["count"]),
        },
      }

      const app = new Vue({
        el: "#app",
        store,
        components: {
          Counter,
        },
        template: `<div>
               <Counter></Counter>
              </div>`,
      })
    </script>
  </body>
</html>
